import React, { Component } from 'react';
import { Card, Button, Checkbox, Form, Input, message } from 'antd';
import style from './index.module.scss'
import { login } from 'api/user'
import logo from 'assets/images/logo.png'
import { setToken } from 'utils/storage';
class Login extends Component {
  state = {
    loadings: false
  }
  render() {
    return (
      <div className={style.login}>
        <Card className='login-container'>
          <img src={logo} alt="" className='login-logo' />
          <Form
            // size='large'
            onFinish={this.onFinish} //依赖name属性，可以拿到表单提交后的数据
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ mobile: '13260659011', code: "246810", agree: true }}  //初始化默认值
            autoComplete="off">
            <Form.Item
              label='Phone'
              name="mobile"
              validateTrigger={["onChange", "onBlur"]}
              rules={[
                { required: true, message: '手机号不能为空！' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }
              ]}>
              <Input placeholder='请输入手机号' />
            </Form.Item>
            <Form.Item
              validateTrigger={["onChange", "onBlur"]}
              label='Code'
              name="code"
              rules={[{ required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码格式错误' }
              ]}>
              <Input.Password placeholder='请输入验证码' />
            </Form.Item>
            <Form.Item
              name="agree"
              rules={[
                {
                  //自定义校验规则
                  validator: (rule, value) => value ? Promise.resolve() :
                    Promise.reject(new Error('请阅读并同意用户协议'))
                }
              ]}
              valuePropName="checked" wrapperCol={{ offset: 6, span: 17 }}>
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
              <Button type="primary" htmlType="submit" loading={this.state.loadings} block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  //依赖name属性，针不搓
  onFinish = async ({ mobile, code }) => {
    this.setState({
      loadings: true
    })
    try {
      let res = await login(mobile, code)
      message.success('登录成功', 1, () => {
        setToken(res.data.token)
        //判断location.sate中是否有值
        console.log(this.props.location);
        this.props.history.push('/home')
        const { state } = this.props.location
        if (state) {
          this.props.history.push(state.from)
        } else {
          this.props.history.push('/home')
        }
      });
    } catch (error) {
      message.error(error.response.data.message, 1, () => {
        this.setState({
          loadings: false
        })
      });
    }
  }
}
export default Login
